﻿using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 销售出库单到应收单单据转换插件
    /// </summary>
    /// <remarks>
    /// 功能：1、携带物料一级分类、二级分类、三级分类
    /// 创建人：lxl
    /// 创建日期：2024-4-27
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [Description("销售出库单到应收单单据转换插件"), HotUpdate]
    public class OutToReceivableCvtPlugin : AbstractConvertPlugIn
    {
        /// <summary>
        /// 解析字段映射关系，并构建查询参数。
        /// 这里可以加入你想要的字段
        /// </summary>
        /// <param name="e">事件参数包</param>
        public override void OnQueryBuilderParemeter(QueryBuilderParemeterEventArgs e)
        {
            //e.SelectItems.Add(new SelectorItemInfo("")); 添加你需要添加的字段的Key
        }

        /// <summary>
        /// 创建关联关系后事件
        /// </summary>
        /// <param name="e">事件参数包</param>
        public override void OnAfterCreateLink(CreateLinkEventArgs e)
        {

        }

        /// <summary>
        /// 下推/选单时，根据字段映射,向目标字段填充值
        /// </summary>
        /// <param name="e"></param>
        public override void OnFieldMapping(FieldMappingEventArgs e)
        {
            switch (e.TargetField.Key.ToUpperInvariant())
            {
                //case "FXXX": 选单时的目标字段Key【大写】，可以根据条件设置值e.MapValue
                //    e.MapValue = "";
                //   break;
                case "":
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 下推/选单，自动填充目标字段值完毕后，这里可以对填充值进行修复，处理
        /// </summary>
        /// <param name="e"></param>
        public override void OnAfterFieldMapping(AfterFieldMappingEventArgs e)
        {
            //SetFilter(e);
        }

        /// <summary>
        /// 最后触发：单据转换后事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterConvert(AfterConvertEventArgs e)
        {
            ExtendedDataEntity[] allBillDataObjs = e.Result.FindByEntityKey("FBillHead");
            //遍历单据转换之后的数据
            foreach (ExtendedDataEntity fHeadData in allBillDataObjs)
            {
                //获取单据体
                DynamicObjectCollection myDataEntity = fHeadData["AP_PAYABLEENTRY"] as DynamicObjectCollection;
                //遍历单据体
                foreach (DynamicObject obj in myDataEntity)
                {
                    string fgroupLevel1 = "";//一级物料
                    string fgroupLevel2 = "";//二级物料
                    string fgroupLevel3 = "";//三级物料
                    string fgroupLevelNumber1 = "";//一级物料编码
                    string fgroupLevelNumber2 = "";//二级物料编码
                    string fgroupLevelNumber3 = "";//三级物料编码
                    //获取物料
                    DynamicObject fmaterialObj = obj["MATERIALID"] as DynamicObject;
                    //获取物料id
                    string fmaterialId = fmaterialObj?["id"].ToString() ?? "0";
                    string strSql = $@"/*dialect*/with grouplevel as (select c.fname fgroup,b.fnumber fgroupnumber,b.fparentid,1 as fgrouplevel from T_BD_MATERIAL a inner join 
                        T_BD_MATERIALGROUP b on  a.FMATERIALGROUP =b.FID and  a.fmaterialid={fmaterialId} 
                        inner join T_BD_MATERIALGROUP_l c on b.FID=c.fid 
                        union all select c.fname,b.fnumber fgroupnumber,b.fparentid ,fgrouplevel+1 from grouplevel a inner join
                        T_BD_MATERIALGROUP b on a.fparentid=b.FID  inner join T_BD_MATERIALGROUP_l c on b.FID=c.fid )
                        select fgroup,fgroupnumber from grouplevel order by fgrouplevel desc  ";
                    DynamicObjectCollection getMtrlGarouObj = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                    if (getMtrlGarouObj.Count == 3)
                    {
                        fgroupLevel1 = Convert.ToString(getMtrlGarouObj[0]["fgroup"]);//一级物料
                        fgroupLevel2 = Convert.ToString(getMtrlGarouObj[1]["fgroup"]);//二级物料
                        fgroupLevel3 = Convert.ToString(getMtrlGarouObj[2]["fgroup"]);//三级物料
                        fgroupLevelNumber1 = Convert.ToString(getMtrlGarouObj[0]["fgroupnumber"]);//一级物料编码
                        fgroupLevelNumber2 = Convert.ToString(getMtrlGarouObj[0]["fgroupnumber"]);//二级物料编码
                        fgroupLevelNumber3 = Convert.ToString(getMtrlGarouObj[0]["fgroupnumber"]);//三级物料编码
                    }
                    else if (getMtrlGarouObj.Count == 2)
                    {
                        fgroupLevel1 = Convert.ToString(getMtrlGarouObj[0]["fgroup"]);//一级物料
                        fgroupLevel2 = Convert.ToString(getMtrlGarouObj[1]["fgroup"]);//二级物料
                        fgroupLevelNumber1 = Convert.ToString(getMtrlGarouObj[0]["fgroupnumber"]);//一级物料编码
                        fgroupLevelNumber2 = Convert.ToString(getMtrlGarouObj[0]["fgroupnumber"]);//二级物料编码
                    }
                    else if (getMtrlGarouObj.Count == 1)
                    {
                        fgroupLevel1 = Convert.ToString(getMtrlGarouObj[0]["fgroup"]);//一级物料
                        fgroupLevelNumber1 = Convert.ToString(getMtrlGarouObj[0]["fgroupnumber"]);//一级物料编码
                    }

                    obj["F_RDLV_MaterialGroup1"] = fgroupLevel1;
                    obj["F_RDLV_MaterialGroup2"] = fgroupLevel2;
                    obj["F_RDLV_MaterialGroup3"] = fgroupLevel3;
                    obj["F_RDLV_MtrlGroupNumber1"] = fgroupLevelNumber1;
                    obj["F_RDLV_MtrlGroupNumber2"] = fgroupLevelNumber2;
                    obj["F_RDLV_MtrlGroupNumber3"] = fgroupLevelNumber3;
                }
            }
        }


    }
}